package cn.com.cfae.iras.doc.analyze.components.consistency;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 信息一致性
 * 抓取首页、M-3章节发行人条款的债务融资工具名称，比较期数、年度、品种是否一致；
 * 预评/发行阶段
 */

@Component("U1001")
@Scope("prototype")
public class U1001 extends BaseComponent {
    private static Logger logger = LoggerFactory.getLogger(U1001.class);
    @Autowired
    private HandingData handingData;
    @Override
    public List<ComponentResult> handlerM() {
        logger.info("获取U1001组件M");
        List<ComponentResult> componentResults = checkRulesU1001(getCatalogId(),"M-0","M-3",getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        logger.info("获取U1001组件BM");
        List<ComponentResult> componentResults = checkRulesU1001(getCatalogId(),"BM-0","BM-3",getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        logger.info("获取U1001组件DM");
        List<ComponentResult> componentResults = checkRulesU1001(getCatalogId(),"DM-0","DM-3",getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        logger.info("获取U1001组件BDM");
        List<ComponentResult> componentResults = checkRulesU1001(getCatalogId(),"BDM-0","BDM-3",getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    private List<ComponentResult> checkRulesU1001(String model,String tableId1,String tableId2,String catalogId,String chapterId,String ruleName){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;
        List<ComponentResult.TextPosition> contentAndPositionList = null;
        int startPage = 0;
        int pageNum = 0;
        boolean flag = false;
        String m0Text = null;
        String m3Text = null;


        List<ComponentResult.TextPosition> m0ContentAndPositionList = null;
        int m0PageNum = 0;
        int m0StartPage = 0;


        boolean isAllErr = false;
        boolean isAllSeem = false;
        try {

            if (extractData!=null){


                ChapterModel m0ChapterModel = extractData.getChapterModel(tableId1);
                m0StartPage =m0ChapterModel!=null?m0ChapterModel.getStartPage():1;
                KVText m0KvTextValue = getKVTextValue(tableId1, "FXTK", "ZWRZGJMC");
                m0PageNum = m0KvTextValue!=null?m0KvTextValue.getPageNumber():m0StartPage;
                m0PageNum = m0PageNum!=0?m0PageNum:m0StartPage;
                m0ContentAndPositionList = m0KvTextValue!=null?getContentAndPositionList(m0KvTextValue):null;
                if (m0KvTextValue!=null){
                     m0Text= m0KvTextValue.getText();
                     if (StringUtils.isNotEmpty(m0Text)){
                         m0Text = m0Text.replaceAll("\\s","");
                     }
                }

                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPage = chapterModel!=null?chapterModel.getStartPage():0;
                KVText m3KvTextValue = getKVTextValue(tableId2, "FXTK", "ZWRZGJMC");
                KVText m3kvTextKey = getKVTextKey(tableId2, "FXTK", "ZWRZGJMC");
                pageNum = m3KvTextValue!=null?m3KvTextValue.getPageNumber():startPage;
                pageNum = pageNum!=0?pageNum:startPage;
                contentAndPositionList = m3kvTextKey!=null?getContentAndPositionList(m3kvTextKey):null;
                if (m3KvTextValue!=null){
                    m3Text= m3KvTextValue.getText();
                    if (StringUtils.isNotEmpty(m3Text)){
                        m3Text = m3Text.replaceAll("\\s","");
                    }
                }
            }

            if (StringUtils.isNotEmpty(m0Text)){
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"抽取首页名称:"+m0Text,"已抽取",false,getRegulationId(), m0PageNum,m0ContentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"抽取首页名称","未识别,建议人工核对",true,getRegulationId(), m0PageNum,m0ContentAndPositionList,"03");
                componentResults.add(componentResult);
            }
            if (StringUtils.isNotEmpty(m3Text)){
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"抽取"+tableId2+"章节名称:"+m3Text,"已抽取",false,getRegulationId(), pageNum,contentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"抽取"+tableId2+"章节名称","未识别,建议人工核对",true,getRegulationId(), pageNum,contentAndPositionList,"03");
                componentResults.add(componentResult);
            }

            if (StringUtils.isNotEmpty(m0Text)&&StringUtils.isNotEmpty(m3Text)){
                String regx = "\\d+|[一二三四五六七八九十]|[中长超短]";
                Pattern pattern = Pattern.compile(regx);
                int m0Index = 0 ;
                int m3Index = 0;
                for (int i=0;i<m0Text.length()-1;i++){
                    char a = m0Text.charAt(i);
                    if(a>='0' && a<='9'){
                       m0Index = i;
                        break;
                    }
                }
                for (int i=0;i<m3Text.length()-1;i++){
                    char a = m3Text.charAt(i);
                    if(a>='0' && a<='9'){
                        m3Index = i;
                        break;
                    }
                }
                m0Text = m0Text.substring(m0Index,m0Text.length()-1);
                m3Text = m3Text.substring(m3Index,m3Text.length()-1);

                StringBuffer m0But = new StringBuffer();
                StringBuffer m3But = new StringBuffer();

                Matcher matcher = pattern.matcher(m0Text);
                while (matcher.find()){
                    m0But.append(matcher.group());
                }
                matcher = pattern.matcher(m3Text);
                while (matcher.find()){
                    m3But.append(matcher.group());
                }

                if (StringUtils.isNotEmpty(m0But.toString())&&StringUtils.isNotEmpty(m3But.toString())&&m0But.toString().equals(m3But.toString())){
                    flag = true;
                }else if (m0Text.equals(m3Text)){
                    flag = true;
                }

                if (flag){
                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"债务融资工具名称检查","内容一致",false,getRegulationId(), pageNum,contentAndPositionList,"01");
                    componentResults.add(componentResult);
                }else {
                    isAllErr = true;
                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"债务融资工具名称检查","不一致,请人工核对",true,getRegulationId(), pageNum,contentAndPositionList,"02");
                    componentResults.add(componentResult);
                }
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"债务融资工具名称检查","未识别,请人工核对",true,getRegulationId(), pageNum,contentAndPositionList,"03");
                componentResults.add(componentResult);
            }
            if (isAllErr){
                for (ComponentResult result:componentResults){
                    result.setExist("02");
                }
            }
            if (isAllSeem){
                for (ComponentResult result:componentResults){
                    result.setExist("03");
                }
            }

        }catch (Exception e){
            componentResults.clear();
            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"债务融资工具名称检查","未识别,建议人工核对",true,getRegulationId(), startPage,contentAndPositionList,"03");
            componentResults.add(componentResult);
            logger.error(e.getMessage(),e);
        }
        return componentResults;
    }


}
